#include "colormaker.h"
#include <QTimerEvent>
#include <QDateTime>

ColorMaker::ColorMaker(QObject *parent)
    : QObject(parent)
    ,m_algorithm(RandomRGB) //初始化一个随机的颜色算法
    ,myColor(Qt::black) //初始化赋值为黑色
    ,m_nColorTimer(0)
{
    qsrand(QDateTime::currentDateTime().toTime_t());
}

ColorMaker::~ColorMaker()
{

}

//调用该函数，确定设置颜色顺便会发射颜色改变的信号
QColor ColorMaker::color() const
{
    return myColor;
}

void ColorMaker::setColor(const QColor &color)
{
    myColor = color;
    emit colorChanged(myColor);
}
QColor ColorMaker::timeColor() const
{
    QTime time = QTime::currentTime();
    int r = time.hour();
    int g = time.minute()*2;
    int b = time.second()*4;
    return QColor::fromRgb(r,g,b);//颜色根据当前时间来生成
}

ColorMaker::GenerateAlgorithm ColorMaker::getAlgorithm() const
{
    return m_algorithm;
}
void ColorMaker::setAlgorithm(GenerateAlgorithm algorithm)
{
    m_algorithm = algorithm;//赋值给类成员
}

void ColorMaker::start()//开启定时器
{
    if(m_nColorTimer == 0)
    {
        m_nColorTimer = startTimer(100);//使用一个周期为1000毫秒的定时器来产生颜色
    }
}
void ColorMaker::stop(){
    if(m_nColorTimer > 0)
    {
        killTimer(m_nColorTimer);//停止定时器的使用
        m_nColorTimer = 0;
    }
}

//timerEvent事件消息
void ColorMaker::timerEvent(QTimerEvent *event)
{
    static unsigned char u8_cnt=0;
    if(event->timerId() == m_nColorTimer)
    {
        switch (m_algorithm) {
        case RandomRGB:
            myColor.setRgb(qrand()%255, qrand()%255, qrand()%255);
            break;
        case RandomRed:
            //myColor.setRed(qrand()%255);
            myColor.setRed(u8_cnt);  u8_cnt>254?u8_cnt=0:u8_cnt+=10;
            break;
        case RandomGreen:
            myColor.setGreen(u8_cnt); u8_cnt>254?u8_cnt=0:u8_cnt+=10;
            break;
        case RandomBlue:
            myColor.setBlue(u8_cnt);u8_cnt>254?u8_cnt=0:u8_cnt+=10;
            break;
        case LinearIncrease:
        {
            int r = myColor.red() + 10;
            int g = myColor.green() + 10;
            int b = myColor.blue() + 10;
            myColor.setRgb(r%255,g%255,b%255);
        }
            break;
        default:
            break;
        }
        //定时器触发时根据算法计算新的颜色值，发射colorChanged信号，同时也发送一个currentTime信号
        emit colorChanged(myColor);
        emit currentTimer(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }
    else
    {
        QObject::timerEvent(event);
    }
}
